/**
 * 
 */
package com.gr.staffpm.pages.admin.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.form.palette.Palette;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.util.CollectionModel;
import org.apache.wicket.model.util.ListModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.joda.time.Instant;

import com.gr.staffpm.datatypes.Group;
import com.gr.staffpm.datatypes.Role;
import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.pages.behaviour.FocusOnLoadBehavior;
import com.gr.staffpm.security.service.UserService;
import com.gr.staffpm.user.changepassword.ChangePasswordPanel;


/**
 * @author Graham Rhodes 31 Dec 2010 13:46:01
 */
public class EditUserForm extends Form<User> {

    private static final long serialVersionUID = 1L;
    private final Palette<Role> rolesPalette;
    private final Palette<Group> groupsPalette;
    private final TextField<String> firstName;
    private final TextField<String> lastName;
    private final TextField<String> emailAddress;
    private final ModalWindow changePasswordWindow;
    private final UserService userService;
    private final User user;

    /**
     * @param id
     * @param model
     */
    public EditUserForm(String id, final UserService userService, final User user) {
        super(id, new CompoundPropertyModel<User>(user));
        this.userService = userService;
        this.user = user;

        firstName = new TextField<String>("firstName");
        firstName.add(new FocusOnLoadBehavior());
        firstName.setRequired(true);
        add(firstName);

        lastName = new TextField<String>("lastName");
        lastName.setRequired(true);
        add(lastName);

        AjaxButton changePassword = new AjaxButton("changePassword") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                launchChangePasswordWindow(target);
            }

        };
        changePassword.setDefaultFormProcessing(false);
        add(changePassword);

        emailAddress = new TextField<String>("emailAddress");
        emailAddress.add(EmailAddressValidator.getInstance());
        emailAddress.setRequired(true);
        add(emailAddress);

        List<Role> roles = userService.getAllRoles();
        IChoiceRenderer<Role> roleRenderer = new ChoiceRenderer<Role>("role", "roleId");
        rolesPalette = new Palette<Role>("roles", new ListModel<Role>(new ArrayList<Role>()), new CollectionModel<Role>(roles), roleRenderer, 10, false);
        rolesPalette.setDefaultModelObject(user.getRoles());
        add(rolesPalette);

        List<Group> groups = userService.getAllGroups();
        IChoiceRenderer<Group> groupRenderer = new ChoiceRenderer<Group>("name", "groupId");
        groupsPalette = new Palette<Group>("groups", new ListModel<Group>(new ArrayList<Group>()), new CollectionModel<Group>(groups), groupRenderer, 10, false);
        groupsPalette.setDefaultModelObject(user.getGroups());
        add(groupsPalette);

        add(changePasswordWindow = new ModalWindow("changePasswordWindow"));

        changePasswordWindow.setInitialHeight(200);
        changePasswordWindow.setInitialWidth(380);
        changePasswordWindow.setContent(new ChangePasswordPanel(changePasswordWindow.getContentId(), userService, user, changePasswordWindow));
        changePasswordWindow.setTitle("Change User Password");
        changePasswordWindow.setCookieName("change-user-password");

        add(new AjaxButton("saveButton", this) {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                this.onSubmit();
            }

        });

        AjaxButton cancel = new AjaxButton("cancelButton") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                setResponsePage(AdminUsersPage.class);
            }

        };
        cancel.setDefaultFormProcessing(false);
        add(cancel);
    }

    protected void launchChangePasswordWindow(AjaxRequestTarget target) {
        changePasswordWindow.show(target);
    }

    /* (non-Javadoc)
     * @see org.apache.wicket.markup.html.form.Form#onSubmit()
     */
    @Override
    @SuppressWarnings("unchecked")
    protected void onSubmit() {
        User currUser = userService.getCurrentUser();

        user.setFirstName(firstName.getValue());
        user.setLastName(lastName.getValue());
        user.setEmailAddress(emailAddress.getValue());
        user.setLastUpdated(new Instant().toDate());
        user.setUpdatedBy(currUser);
        user.getRoles().addAll((Set<Role>) rolesPalette.getDefaultModelObject());
        user.getGroups().addAll((Set<Group>) groupsPalette.getDefaultModelObject());

        userService.addOrUpdateUser(user);

        //Send user back to previous page
        setResponsePage(AdminUsersPage.class);
    }

}
